package com.yh.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yh.model.Permission;
import com.yh.model.Role;
import com.yh.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.security.RolesAllowed;
import java.util.List;

@Controller
@RequestMapping("role")
public class RoleController {
    @Autowired
    RoleService roleService;

    @RolesAllowed("ADMIN")
    @RequestMapping("findAll")
    public String findAll(@RequestParam(name="page",defaultValue = "1")  int page,
                          @RequestParam(name="size",defaultValue = "5") int size,
                          Model model ) {
        PageHelper.startPage(page,size);
        List<Role> roleList = roleService.findAll();
        PageInfo<Role> pageInfo = new PageInfo<>(roleList);
        model.addAttribute("pageInfo",pageInfo);
        return "role-list";
    }

    @RequestMapping("save")
    public String save(Role role) {
        roleService.save(role);
        return "redirect:findAll";
    }

    // role/findById(id=
    /**
     * 根据角色id查询角色详情(角色 权限)
     * @param id 角色id
     * @param model 封装模型数据
     * @return 渲染角色详情页面
     */
    @GetMapping("findById")
    public String findById(@RequestParam("id") Integer id, Model model) {
        Role role = roleService.findById(id);
        model.addAttribute("role",role);
        return "role-show";
    }

    //查询角色没有的权限集合
    //  /role/findRoleByIdAndAllRole?id=1
    @RequestMapping("findRoleByIdAndAllPermission")
    public String findRoleByIdAndAllPermission(@RequestParam("id") Integer id, Model model) {
        //角色可以添加的权限集合
        List<Permission> permissionList = roleService.findOthersPermissionByRoleId(id);
        Role role = new Role();
        role.setId(""+id);
        model.addAttribute("role",role);
        //角色可添加的角色集合
        model.addAttribute("permissionList",permissionList);
        return "role-permission-add";
    }

    //为角色分配权限(关系表)
    @RequestMapping("addPermissionToRole")
    public String addPermissionToRole(@RequestParam("roleId") Integer roleId,
                                      @RequestParam("ids") Integer[] ids) {
        roleService.addPermissionToRole(roleId,ids);
        return "redirect:findById?id="+roleId;
    }

    //删除指定角色(并且删除关系表中的关联数据)
    //deleteRole?id=6
    @RequestMapping("deleteRole")
    public String deleteRole(@RequestParam("id") Integer id) {
        roleService.deleteRole(id);
        return "redirect:findAll";
    }
}
